﻿#region Copyright
// Copyright (c) 2011-2012 RaisingForce Team (Alikin Sergey)
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Windows.Controls;

namespace RaisingForce.Raise.Presentation.Rules
{
    public abstract class BaseValidationRule<T> :
        ValidationRule
    {
        #region Constructors

        protected BaseValidationRule()
        { }

        #endregion

        #region Properties

        private const string exceptionMessage =
            "{0} property should be a non-whitespace string.";

        private string errorText;

        public string ErrorText
        {
            get
            {
                Contract.Ensures(ValidationRuleRules.ErrorTextIsValid(Contract.Result<string>()));
                return this.errorText ?? "Property is invalid.";
            }
            set
            {
                if (!ValidationRuleRules.ErrorTextIsValid(value))
                {
                    throw new ArgumentException(
                        string.Format(exceptionMessage, "ErrorText"));
                }
                Contract.EndContractBlock();
                this.errorText = value;
            }
        }

        private string errorEmptyText;

        public string ErrorEmptyText
        {
            get
            {
                Contract.Ensures(ValidationRuleRules.ErrorTextIsValid(Contract.Result<string>()));
                return this.errorEmptyText ?? "Property is empty.";
            }
            set
            {
                if (!ValidationRuleRules.ErrorTextIsValid(value))
                {
                    throw new ArgumentException(
                        string.Format(exceptionMessage, "ErrorEmptyText"));
                }
                Contract.EndContractBlock();
                this.errorEmptyText = value;
            }
        }

        #endregion

        #region Protected Declarations

        protected abstract bool TryParse(
            string s,
            NumberStyles style,
            IFormatProvider provider,
            out T value);

        protected abstract bool IsValid(T value);

        #endregion

        #region Base Overrides

        public override ValidationResult Validate(
           object value,
           CultureInfo cultureInfo)
        {
            T convertedValue;
            if (value is T)
            {
                convertedValue = (T)value;
            }
            else
            {
                string valueText = (string)value;
                if (string.IsNullOrWhiteSpace(valueText))
                {
                    return new ValidationResult(false, this.ErrorEmptyText);
                }
                if (!this.TryParseValue(valueText, cultureInfo, out convertedValue))
                {
                    return new ValidationResult(false, this.ErrorText);
                }
            }
            if (!this.IsValid(convertedValue))
            {
                return new ValidationResult(false, this.ErrorText);
            }
            return new ValidationResult(true, null);
        }

        #endregion

        #region Public Methods

        public bool TryParseValue(string s, CultureInfo cultureInfo, out T value)
        {
            return this.TryParse(s, NumberStyles.Any, cultureInfo, out value);
        }

        public bool TryParseValue(string s, out T value)
        {
            return this.TryParseValue(s, CultureInfo.CurrentCulture, out value);
        }

        #endregion
    }
}
